package com.situ.onlinebookstore.front.interceptor;

import com.situ.onlinebookstore.common.vo.Result;
import com.situ.onlinebookstore.common.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (ObjectUtils.isEmpty(user)) {
            if (request.getRequestURI().contains("/api/")) {
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write(
                        Result.error(5,"用户未登录，请登陆后再操作！").toJson()
                );
            } else {
                //没登陆
                //页面请求重定向到登录页面
                response.sendRedirect("/user/login");
            }
            //json请求，返回一个错误信息请先登录
            return false;
        }
        //登陆了
        return true;
    }
}
